﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using MatthiWare.PortChecker.Events;

namespace MatthiWare.PortChecker
{
    public class PortChecker
    {
        private delegate void StartDelegate(StatusCallback scb);

        public event EventHandler<PortEventArgs> PortCheckCompleted;
        internal bool _running = false;
        public UInt16 MinimumPort { get; set; }
        public UInt16 MaximumPort { get; set; }
        public IPAddress Ip { get; set; }

        public PortChecker(UInt16 minPort, UInt16 maxPort, IPAddress ip)
        {
            MinimumPort = minPort;
            MaximumPort = maxPort;
            Ip = ip;
        }

        public void StartChecking(StatusCallback scb)
        {
            _running = true;
            StartDelegate sd = new StartDelegate(Start);
            sd.BeginInvoke(scb, (ar) => { scb.Invoke("Waiting for answer..."); }, null);

        }

        private void Start(StatusCallback scb)
        {
            for (UInt16 i = MinimumPort; i <= MaximumPort; i++)
            {
                if (!_running)
                    return;

                CheckPortTask task = new CheckPortTask(PortCheckCompleted, Ip);
                task.BeginCheckPort(i);
            }

            _running = false;
        }

        public void End()
        {
            _running = false;
        }
    }
}
